package com.example.springbootblog.config;


import com.example.springbootblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


@Configuration
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("user_token");
        log.info("从header中获取token, token:"+token);
        if(!StringUtils.hasLength(token)) {
            return false;
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            // 非法 token
            response.setStatus(401);
            return false;
        }
        return true;
    }
}